namespace Digitalmes.Application.Mes;

/// <summary>
/// 工艺步序表服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "mes")]
public sealed class ProcProcessParamsService : IDynamicWebApiService
{
    private readonly SugarRepository<ProcProcessParams> _thisRepository;

    public ProcProcessParamsService(SugarRepository<ProcProcessParams> thisRepository)
    {
        _thisRepository = thisRepository;
    }

    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<ProcProcessParamsDto>> GetPagesAsync(ProcProcessParamsPageParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .Where(s => s.ProcessId == param.ProcessId && !s.IsDisabled)
            .OrderBy(s => new { s.ProductId, s.TagName, s.Step })
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<ProcProcessParamsDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<ProcProcessParamsDto> GetAsync(long id)
    {
        var model = await _thisRepository.GetByIdAsync(id);
        return model.Adapt<ProcProcessParamsDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> AddAsync(ProcProcessParamsDto model)
    {
        // 工序、产品 和 标记名称 和 步序号 唯一
        if (await _thisRepository.IsAnyAsync(s => s.ProcessId == model.ProcessId 
            && s.ProductId == model.ProductId
            && s.TagName == model.TagName
            && s.Step == model.Step))
        {
            Oops.ThrowBah(ErrCode.E4005);
        }

        return await _thisRepository.InsertAsync(model.Adapt<ProcProcessParams>());
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(ProcProcessParamsDto model)
    {
        if (await _thisRepository.IsAnyAsync(s => s.ProcessId == model.ProcessId 
            && s.ProductId == model.ProductId
            && s.TagName == model.TagName
            && s.Step == model.Step
            && s.Id != model.Id))
        {
            Oops.ThrowBah(ErrCode.E4002);
        }

        var item = model.Adapt<ProcProcessParams>();

        return await _thisRepository.UpdateAsync(item, m => new
        {
            m.StdLower,
            m.StdHigher,
            m.UpdateUser,
            m.UpdateTime,
        });
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody] List<long> ids) =>
        await _thisRepository.DeleteAsync(m => ids.Contains(m.Id));
}
